package cn.edu.zust.se.service.file.utils;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@Slf4j

public class SimpleFileUtil {
    public static Integer getFileTypeCode(MultipartFile file) {
        String suffix = FileUtil.extName(file.getOriginalFilename());
        if (suffix != null) {
            switch (suffix) {
                case "png", "jpg", "jpeg", "gif","bmp" -> {
                    return 0;
                }
                case "mp4", "avi", "mkv", "mov" ->{
                    return 1; // 视频
                }
                case "mp3","wav","flac","aac" ->{
                    return 2; // 音频
                }
                case "pdf", "doc", "docx", "txt" ->{
                    return 3; // 文档
                }
                default -> {
                    return 4; // 其他
                }
            }
        }
        return null;
    }
    public static Integer getTypeByFile(File file){
        String name = file.getName();
        String suffix = FileUtil.extName(name);
        if (suffix != null) {
            switch (suffix) {
                case "png", "jpg", "jpeg", "gif","bmp" -> {
                    return 0;
                }
                case "mp4", "avi", "mkv", "mov" ->{
                    return 1; // 视频
                }
                case "mp3","wav","flac","aac" ->{
                    return 2; // 音频
                }
                case "pdf", "doc", "docx", "txt" ->{
                    return 3; // 文档
                }
                default -> {
                    return 4; // 其他
                }
            }
        }
        return null;
    }

    /**
     *
     * <p>Title: getContent</p>
     * <p>Description:根据文件路径读取文件转出byte[] </p>
     * @param filePath
     * @return 字节数组
     * @throws IOException
     */
    public static byte[] getContent(String filePath) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            log.info("file too big...");
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        // 确保所有数据均被读取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        fi.close();
        return buffer;
    }

    public static String getExtName(String filename) {
        return FileUtil.extName(filename);
    }
}
